package com.dgut.forum.controller;

import com.dgut.forum.common.AppResult;
import com.dgut.forum.common.MessageState;
import com.dgut.forum.common.ResultCode;
import com.dgut.forum.config.AppConfig;
import com.dgut.forum.exception.ApplicationException;
import com.dgut.forum.model.Message;
import com.dgut.forum.model.User;
import com.dgut.forum.services.impl.MessageServiceImpl;
import com.dgut.forum.services.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Slf4j
@RestController
@Api(tags="私信接口")
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageServiceImpl messageService;
    @Autowired
    private UserServiceImpl userService;
    @ApiOperation("发生私信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("私信接收者Id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("私信正文") @RequestParam("content") @NonNull String content){

        //获取用户信息
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断获取的用户状态
        if(user==null||user.getDeleteState()==1){
            log.warn("发送私信,发送者用户不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if(user.getState()==1){
            log.warn("用户被禁言,无法发送私信,user="+user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        if(!user.getId().equals(user.getId())){
            log.warn("没有权限私用此用户Id发送私信");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_HAVE_NOT_PERMISSION));
        }
        if(user.getId()==receiveUserId){
            log.info("不能给自己发送私信");
            throw new ApplicationException(AppResult.failed("不能给自己发送私信"));
        }


        //校验接收者存在否
        User receive=userService.selectByPrimaryKey(receiveUserId);
        //判断获取的用户状态
        if(receive==null||receive.getDeleteState()==1){
            log.warn("发送私信,接受用户不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        Message message=new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        messageService.createMessage(message);

        log.info("发送私信成功");
        return AppResult.success();
    }


    @ApiOperation("查看私信个数")
    @GetMapping("/getUnreadCount")
    public AppResult getUnreadCount(HttpServletRequest request){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user==null){
            log.error("查看私信未读个数,发生服务器错误");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        int count=messageService.selectMessageUnRead(user.getId());
        return AppResult.success(count);
    }


    @ApiOperation("查看私信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user==null){
            log.error("查看私信未读个数,发生服务器错误");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        List<Message> ret=messageService.getAll(user.getId());
        log.info("获取私信成功");
        return AppResult.success(ret);
    }


    @ApiOperation("修改私信状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(@ApiParam("私信Id") @RequestParam("id") @NonNull Long id){
        Message message=messageService.selectById(id);
        if(message==null){
            log.info("修改私信状态,私信不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        messageService.updateState(id, MessageState.READ.getType());
        log.info("修改私信状态为已读成功");
        return AppResult.success();
    }

    @ApiOperation("回复私信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("私信Id") @RequestParam("id") @NonNull Long id,
                           @ApiParam("回复内容") @RequestParam("content") @NonNull String content){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user==null){
            log.error("查看私信未读个数,发生服务器错误");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //获取原私信信息
        Message existsMessage=messageService.selectById(id);
        if(existsMessage==null){
            log.info("回复私信,查看原私信状态,原私信不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        //校验回复与原私信是否是同一个人
        if(user.getId()==existsMessage.getPostUserId()){
            log.warn("不能给自己发送私信");
            throw new ApplicationException(AppResult.failed("不能给自己发送私信"));
        }
        if(user.getId()!=existsMessage.getReceiveUserId()){
            log.warn("您无权回复不属于你的私信");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_HAVE_NOT_PERMISSION));
        }

        Message message=new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);

        messageService.reply(id,message);
        log.info("回复私信成功");
        return AppResult.success();
    }
}
